<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 13.4.2</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="13.4.1.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="13.4.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P2">Part II. Tables and Objects</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#13">Chapter 13. Metatables and Metamethods</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h3>13.4.2 &ndash; The <code>__newindex</code> Metamethod</h3>

<p>The <code>__newindex</code> metamethod does for table updates what
<code>__index</code> does for table accesses.
When you assign a value to an absent index in a table,
the interpreter looks for a <code>__newindex</code> metamethod:
If there is one, the interpreter calls it
<em>instead of</em> making the assignment.
Like <code>__index</code>, if the metamethod is a table,
the interpreter does the assignment in that table,
instead of in the original one.
Moreover, there is a raw function that
allows you to bypass the metamethod:
The call <code>rawset(t, k, v)</code> sets the value <code>v</code> in key <code>k</code>
of table <code>t</code> without invoking any metamethod.

<p>The combined use of <code>__index</code> and <code>__newindex</code> metamethods
allows several powerful constructs in Lua,
from read-only tables to tables with default values to
inheritance for object-oriented programming.
In the rest of this chapter we see some of these uses.
Object-oriented programming has its own chapter.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="13.4.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

